/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.web;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.*;
import com.thinkgem.jeesite.modules.sys.service.*;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.util.List;


/**
 * 用户Controller
 * @author ThinkGem
 * @version 2013-8-29
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/manageTenenment")
public class ManagerTenementController extends BaseController {

	@Autowired
	private AgentTenementService agentTenementService;
	@Autowired
	private AddTenementInfoService addTenementInfoService;
	@Autowired
	private CommunityService communityService;
	@Autowired
	private ShopAddService shopAddService;
	@Autowired
	PC service;
	@Autowired
	private TbCommunityService tbCommunityService;


	//代理商查看他所代理的市下的所有物业信息
	@RequestMapping(value = "/manageTenementList")
	public String list(TbUserTenementInfo tbUserTenementInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<TbUserTenementInfo> page = agentTenementService.manageTenementList(new Page<TbUserTenementInfo>(request, response),tbUserTenementInfo);
        model.addAttribute("page", page);
		if(page.getList().size()==0){
			model.addAttribute("message1","无查询结果");
		}
		return "modules/sys/manageTenementList";
	}
	@RequestMapping(value="form")
	public String form(TbUserTenementInfo tbUserTenementInfo,Model model){
		if(tbUserTenementInfo.getId()!=null){
			tbUserTenementInfo=addTenementInfoService.getById(tbUserTenementInfo);
		}
		//添加时已制定他所在的小区小区,根据物业所管理小区id得到小区名称
		TbCommunity tbCommunity=tbCommunityService.get(Integer.parseInt(UserUtils.getUser().getCommunityId()));
		model.addAttribute("community",tbCommunity);
		tbUserTenementInfo.setCommunityId(tbCommunity.getId());
		//用于存储所管理的小区的名称
		tbUserTenementInfo.setAreaname(tbCommunity.getCommName());
		model.addAttribute("tbUserTenementInfo",tbUserTenementInfo);
		return "modules/sys/manageTenementForm";
	}
	//添加或修改
	@RequestMapping(value="saveTenement")
	public String saveTenement(TbUserTenementInfo tbUserTenementInfo,Model model){
		addTenementInfoService.saveTenementInfo(tbUserTenementInfo);
		return "redirect:" + adminPath + "/sys/manageTenenment/manageTenementList";
	}
	//删除
	@RequestMapping(value="delete")
	public String delete(TbUserTenementInfo tbUserTenementInfo,Model model){
		addTenementInfoService.deleteTenenment(tbUserTenementInfo);
		return "redirect:" + adminPath + "/sys/manageTenenment/manageTenementList";
	}
	/**
	 * 导出物业费用数据
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "exportTenement", method= RequestMethod.POST)
	public String exportTenementFile(TbUserTenementInfo tbUserTenementInfo,User user, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "物业费数据"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			tbUserTenementInfo.setUid(UserUtils.getUser().getId());
			Page<TbUserTenementInfo> page = agentTenementService.manageExportTenementList(
					new Page<TbUserTenementInfo>(request, response,-1),tbUserTenementInfo);
			new ExportExcel("物业费数据", TbUserTenementInfo.class).setDataList(page.getList()).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出物业信息失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/manageTenenment/manageTenementList";
	}
	/**
	 * 导入物业费数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "importTenement", method=RequestMethod.POST)
	public String importTenementFile(MultipartFile file, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {

		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/manageTenenment/manageTenementList";
		}
		try {
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<TbUserTenementInfo> list = ei.getDataList(TbUserTenementInfo.class);
			//小区插入
			TbCommunity tbCommunity = new TbCommunity();
			tbCommunity = communityService.insertManageCommunity(list) ;
			if(tbCommunity!=null){
				String msg=addTenementInfoService.importTenement(list,tbCommunity);
				addMessage(redirectAttributes,msg);
			}else{
				addMessage(redirectAttributes, "导入物业信息失败！失败信息：该小区不存在");
			}

			//addMessage(redirectAttributes, "已成功导入 "+successNum+" 条物业信息"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入物业信息失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/manageTenenment/manageTenementList";
	}
	/**
	 * 下载导入用户数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "import/templateTenement")
	public String importFileTemplateTenement(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "物业表数据导入模板.xlsx";
			List<TbUserTenementInfo> list = Lists.newArrayList(); /*list.add(UserUtils.getUser());*/
			new ExportExcel("物业表数据", TbUserTenementInfo.class, 2).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/manageTenenment/manageTenementList";
	}
	//缴纳物业费
	@RequestMapping(value="tenementMoney")
	public String tenementMoney(TbUserTenementInfo tbUserTenementInfo,RedirectAttributes redirectAttributes,Model model){
		if(null!=tbUserTenementInfo&&null!=tbUserTenementInfo.getUid()&&!"".equals(tbUserTenementInfo.getUid())){
			//物业缴费
		    String isok=	agentTenementService.tenementMoney(tbUserTenementInfo);
			model.addAttribute("message2","物业缴费成功");
		}
		List<TbUserTenementInfo> buildNumList=agentTenementService.getBuildNumList();
		if(buildNumList.isEmpty()){
			model.addAttribute("message2","请在店铺中心的店铺信息中维护店铺所在小区，方便进行物业缴费！");
		}

		model.addAttribute("buildNumList",buildNumList);
		return "modules/sys/tenementMoney";
	}
	//根据楼号得到单元号集合
	@RequestMapping("/showUnitNoList")
	public void showUnitNoList(HttpServletRequest request, HttpServletResponse response, String buildNum) {
		response.setContentType("text/html;charset=UTF-8");
		List<TbUserTenementInfo> buildNumList=agentTenementService.getUnitNumList(buildNum);
		try{
			Gson gson=new Gson();
			response.getWriter().print(gson.toJson(buildNumList));
			response.getWriter().flush();
			response.getWriter().close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	//根据单元号得到門牌號集合
	@RequestMapping("/showDoorNoList")
	public void showDoorNoList(HttpServletRequest request, HttpServletResponse response, String buildNum,Integer unitNo) {
		response.setContentType("text/html;charset=UTF-8");
		List<TbUserTenementInfo> doorNoList=agentTenementService.getDoorNoList(buildNum,unitNo);
		try{
			Gson gson=new Gson();
			response.getWriter().print(gson.toJson(doorNoList));
			response.getWriter().flush();
			response.getWriter().close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	//根据单元号得到門牌號集合
	@RequestMapping("/OneTenement")
	public void OneTenement(HttpServletRequest request, HttpServletResponse response, String buildNum,Integer unitNo,String showName) {
		response.setContentType("text/html;charset=UTF-8");
		List<TbUserTenementInfo>  tbUserTenementInfo=agentTenementService.getTenementInfo(buildNum,unitNo,showName);
		try{
			Gson gson=new Gson();
			response.getWriter().print(gson.toJson(tbUserTenementInfo));
			response.getWriter().flush();
			response.getWriter().close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}

}
